 debug = 1 #debug mode

"""
Universal Model Converter - created by Tcll5850
   ___________________    __    __
  /___   ____________/\  / /\  / /\
  \___/ /\___________\/ / / / / / /
     / / / ________    / / / / / / ______   ______   ______   ______
    / / / / ______/\  / / / / / / / ____/\ / __  /\ / ____/\ / __  /\
   / / / / /\_____\/ / / / / / / /___  /\// __  / //___  /\// /\/ / /
  / / / / /_/___    / / / / / / /_____/ //_____/ //_____/ //_____/ /
 /_/ / /_______/\  /_/ / /_/ /  \_____\/ \_____\/ \_____\/ \_____\/  \_\/  \_______\/  \_\/  \_\/
 \_\/  \_______\/  \_\/  \_\/

email: tcll5850@gmail.com
website: http://tcll5850.hostoi.com

--Revisions--:
0.# series: brute-force methods (scrapped)
1.0a: original (unreleased)
1.0b: plugin system applied
2.0a: GUI styled and edited
2.0b: Conversion Method Button Windows (CMBW) added - (all plugins redone)
2.6b: major internal revisions + overhaul of tmp format + deletion of pyc files
- fixed the file-save error where you had to type the extension
2.6c: defined functions toward the tmp + complete overhaul of the plugins
2.6d: centered around melee to obj conversion + code cleanup and managment

TODO:
get multi-reference conversion working

thanx to everyone who helped: """
#Tonyjv, jcao219, VILE

"""if I'm missing credit where it's due, please let me know. :)"""


vrsn = '2.6c'
from Tkinter import *
root = Tk( )#main loop
#draw the main window
root.geometry("350x140");root.title("UMC "+vrsn);root.maxsize (width=350, height=140);root.minsize (width=350, height=140)
#logo + text:
C = Canvas(bg='black', width=350, height=140); C.grid(row=0, column=0)
C.create_text( 176, 50, fill='#cccccc', text='Universal\nModel Converter', justify=CENTER, font=('Fixedsys', 24, 'bold'))
C.create_text( 72, 110, fill='#cccccc', text='version '+vrsn, font=('Fixedsys', 11))
C.create_text( 285, 110, fill='#cccccc', text='By Tcll5850', font=('Fixedsys', 11))
#_____________________________________________________________________________________________________

#.-- credit to Tonyjv for the following code block: --.
import os, sys #load plugins
plugin_dir, process_dir = (os.path.join(os.path.realpath(os.path.curdir), direct) for direct in ( 'plugins', 'test'))
sys.path.append(plugin_dir); imported_modules = [__import__(fname.split(".")[-2]) for fname in os.listdir(plugin_dir) if fname.endswith('.py')]

def CMBW(btns_list,fl): #Conversion Method Button window
    key,cmds = '','' #'key' = conversion method to use; 'cmds' = dynamic button commands

    #create the window
    BW = Toplevel(takefocus=True)
    BW.title("Conversion Buttons"); BW.maxsize(width=230, height=((len(btns_list)*36)+26)); BW.minsize(width=230, height=((len(btns_list)*36)+26))
    BW.lift ()

    def btn_press(k): #experimental
        #key = k
        #BW.destroy()
        print k #testing
        return k
        
    TXT = Button(BW, width=36, height=1, relief=FLAT, state=DISABLED, disabledforeground='black',
        text=('conversion methods for *.' + str(fl).split(".")[-1] + ' files:')).grid(row=0, column=0)
        #^a simple button used as a text widget (easier to use when centering text)

    for rw, btn in enumerate(btns_list): #add the multiple buttons to the window
        if debug: print str(rw) + ': ' + btn[0] + ' - name: ' + btn[1] #debug
        cmds += str(btn[1]) + '.config(command=btn_press("' + str(btn[0]) + '"))\n' #experimental: add the dynamic command for the button
        btn[1] = Button(BW, width=36, height=2, text=str(btn[0])) #create the button (does nothing right now)
        btn[1].grid(row=(rw+1), column=0) #position the button on the window
        #btn[1].config(command=btn_press(btn[0])) #experimental
        key = btn[1].invoke() #experimental
        #'btn[0]' contains a varification string (a key) that is also used as the text for the button
            #^this is what sets the 'key' var to decide which plugin to use
        #'btn[1]' contains a string to be used as a var to name the button (works perfectly)

    print cmds #testing
    eval(cmds) #experimental
    
    root.wait_window ( BW )#wait until the button window is destroyed
    return key

#support list fmt: "*.type"
#im/ex_types list fmt: ('name','*.type')
support, im_types, ex_types, C_mthds = [], [], [], [] #vars for storing file info, and conversion methods
for module in imported_modules: module.inf(support,im_types,ex_types,C_mthds) #get plugin info
#C_mthds is a required variable attribute (must be present in all plugins)
    
if debug: #debug info
    print str(len(imported_modules)) + ' Plugins'
    for count, module in enumerate(imported_modules): print str(count) + ': ' + str(module) + ' ' + (str(module).split(' ')[1]).split("'")[1] + '.py'
    print; print'supported files: ' + str(" ".join(support))
    print'import types: ' + str(im_types)
    print 'export types: ' + str(ex_types)
    print 'conversion methods: ' + str(C_mthds)

#file-open/save dialogs
from tkFileDialog import askopenfilename, asksaveasfilename #modules
#____________________________________________import block_____________________________________________
    #after opening your file, creates a window to select the type of conversion method to use
    #(if there are 2 or more plugins dedicated to that specific file type)
    
imfl = askopenfilename(filetypes=[('Supported', " ".join(support))]+im_types)#, multiple=1) #prompt
if debug: print; print 'import file: ' + str(imfl).split("/")[-1] #debug info

imkey,imbtns = '',[] #import key / buttons
#CMBW import methods (final check before conversion)
#to select the correct conversion plugin
for C_mthd in C_mthds: #compair the file types and select the buttons to add
    if C_mthd[0] == str(imfl).split(".")[-1]: imbtns.append([C_mthd[1],C_mthd[2]])

#has open dialog been cancelled?
if len(imbtns) > 0:
    #is there only a single associated plugin?
    if len(imbtns) > 1: imkey = CMBW(imbtns,imfl) #draw the button window
    else:
        for imbtn in imbtns: imkey = imbtn[0] #set imkey to the single conversion key
else: #exit the app
    for module in imported_modules: os.remove('plugins/' +\
    (str(module).split(' ')[1]).split("'")[1] + '.pyc') #delete those pesky pyc files before quitting
    quit()
    
if debug: print "imkey = '" + imkey + "'"; print #debug info
#____________________________________________export block_____________________________________________
    #this works the same way as the import block

exfl = asksaveasfilename(initialfile=str((str(imfl).split("/")[-1]).split('.')[0]), filetypes=ex_types,
                         defaultextension='.obj') #bugfix
if debug: print 'export file: ' + str(exfl).split("/")[-1] #debug info

exkey,exbtns = '',[] #export key / buttons
for C_mthd in C_mthds: #compair the file types and select the buttons to add
    if C_mthd[0] == str(exfl).split(".")[-1]: exbtns.append([C_mthd[1],C_mthd[3]])

#has open dialog been cancelled?
if len(exbtns) > 0:
    #is there only a single associated plugin?
    if len(exbtns) > 1: exkey = CMBW(exbtns,exfl) #draw the button window
    else:
        for exbtn in exbtns: exkey = exbtn[0] #set exkey to the single conversion key
else: #exit the app
    for module in imported_modules: os.remove('plugins/' +\
    (str(module).split(' ')[1]).split("'")[1] + '.pyc') #delete those pesky pyc files before quitting
    quit()
    
if debug: print "exkey = '" + exkey + "'"; print #debug info

#__________________________________________conversion block___________________________________________

for module in imported_modules: module.impt(imfl,imkey,debug)#import
for module in imported_modules: module.expt(exfl,exkey,debug)#export

os.remove('global.tmp') #delete global.tmp
for module in imported_modules: os.remove('plugins/' +\
    (str(module).split(' ')[1]).split("'")[1] + '.pyc') #delete those pesky pyc files before quitting
quit()
root.mainloop( )
